import Service from '@ember/service';
import { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';

export default class ApiService extends Service {
  @service call;
  @service message;
  
  // API基础URL
  baseUrl = 'http://10.26.3.112:7010';

  // 用户登录状态
  @tracked isLoggedIn = false;
  @tracked currentUser = null;

  constructor() {
    super(...arguments);
    // 检查是否已有authentication信息
    this.checkExistingAuth();
    
    // 初始化缓存
    this.cachedParticipants = null;
    this.cachedParticipantsTimestamp = null;
    this.cacheExpireTime = 5 * 60 * 1000; // 5分钟缓存
  }

  // 检查已有的authentication信息
  checkExistingAuth() {
    const existingAuth = sessionStorage.getItem('Authentication');
    if (existingAuth) {
      console.log('发现已有的authentication:', existingAuth); // 调试信息
      this.isLoggedIn = true;
      // 这里可以添加验证现有token是否有效的逻辑
    }
  }

  // 用户登录相关接口
  async loginByUserKey(userKey) {
    try {
      const url = `${this.baseUrl}/api/members/userKey/${userKey}`;
      // 使用原始的fetch来获取响应头
      const response = await fetch(url);
      const data = await response.json();
      console.log('登录响应数据:', data); // 调试信息
      
      // 从响应头中获取authentication信息
      const authHeader = response.headers.get('Authentication') ||
                         response.headers.get('authentication') ||
                         response.headers.get('Authorization') ||
                         response.headers.get('authorization');
      console.log('响应头中的authentication:', authHeader); // 调试信息
      
      if (data.success) {
        this.isLoggedIn = true;
        this.currentUser = data.data;
        // 存储authentication信息到sessionStorage
        if (authHeader) {
          console.log('存储authentication:', authHeader); // 调试信息
          sessionStorage.setItem('Authentication', authHeader);
          console.log('存储后的sessionStorage:', sessionStorage.getItem('Authentication')); // 调试信息
        } else {
          console.log('响应头中没有找到authentication信息'); // 调试信息
        }
      }
      return data;
    } catch (error) {
      console.error('用户登录失败:', error);
      return { success: false, code: 500, message: '登录请求失败', data: null };
    }
  }

  // 包装API调用，检查登录状态
  async callWithAuthCheck(method, url, data = null, params = {}) {
    try {
      const response = await this.call[method](url, data, params);
      
      // 检查是否需要跳转到登录页面
      if (response && response.code === 300 && response.message === '用户未登录') {
        this.handleUnauthorized();
        return response;
      }
      
      return response;
    } catch (error) {
      console.error('API调用失败:', error);
      throw error;
    }
  }

  // 处理未授权情况
  handleUnauthorized() {
    this.isLoggedIn = false;
    this.currentUser = null;
    this.message.error('登录已过期，请重新登录');
  }

  // 退出登录
  logout() {
    this.isLoggedIn = false;
    this.currentUser = null;
    // 清除authentication信息
    sessionStorage.removeItem('Authentication');
    // 清除缓存
    this.clearParticipantsCache();
  }

  // 清除参与人员缓存
  clearParticipantsCache() {
    this.cachedParticipants = null;
    this.cachedParticipantsTimestamp = null;
    console.log('已清除参与人员缓存');
  }

  // 检查登录状态
  checkLoginStatus() {
    return this.isLoggedIn;
  }

  // 团队成员相关接口
  async getMembers() {
    try {
      const url = `${this.baseUrl}/api/members`;
      const response = await this.callWithAuthCheck('get', url);
      return response.success ? response.data : [];
    } catch (error) {
      console.error('获取成员列表失败:', error);
      return [];
    }
  }

  async getMembersByType(type) {
    const url = `${this.baseUrl}/api/members/type/${type}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async addMember(memberData) {
    try {
      const url = `${this.baseUrl}/api/members`;
      const response = await this.callWithAuthCheck('post', url, JSON.stringify(memberData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('新增成员失败:', error);
      return null;
    }
  }

  async updateMember(id, memberData) {
    try {
      const url = `${this.baseUrl}/api/members/${id}`;
      const response = await this.callWithAuthCheck('put', url, JSON.stringify(memberData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('更新成员失败:', error);
      return null;
    }
  }

  async deleteMember(id) {
    const url = `${this.baseUrl}/api/members/${id}`;
    const response = await this.callWithAuthCheck('delete', url);
    return response.success ? response.data : null;
  }

  // 项目配置相关接口
  async getProjectConfigs() {
    const url = `${this.baseUrl}/api/project-configs`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async getProjectConfigByKey(key) {
    const url = `${this.baseUrl}/api/project-configs/key/${key}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : null;
  }

  async deleteProjectConfig(id) {
    const url = `${this.baseUrl}/api/project-configs/${id}`;
    const response = await this.callWithAuthCheck('delete', url);
    return response.success ? response.data : null;
  }

  // 需求相关接口
  async getRequirements(params = {}) {
    try {
      const url = `${this.baseUrl}/api/requirements`;
      const response = await this.callWithAuthCheck('get', url, null, params);
      return response.success ? response.data : [];
    } catch (error) {
      console.error('获取需求列表失败:', error);
      return [];
    }
  }

  async getRequirementsByStatus(status) {
    const url = `${this.baseUrl}/api/requirements/status/${status}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async addRequirement(requirementData) {
    try {
      const url = `${this.baseUrl}/api/requirements`;
      const response = await this.callWithAuthCheck('post', url, JSON.stringify(requirementData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('新增需求失败:', error);
      return null;
    }
  }

  async updateRequirement(id, requirementData) {
    try {
      const url = `${this.baseUrl}/api/requirements`;
      const response = await this.callWithAuthCheck('put', url, JSON.stringify(requirementData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('更新需求失败:', error);
      return null;
    }
  }

  async deleteRequirement(id) {
    const url = `${this.baseUrl}/api/requirements/${id}`;
    const response = await this.callWithAuthCheck('delete', url);
    return response.success ? response.data : null;
  }

  // 隐藏日期相关接口
  async getHiddenDates() {
    try {
      const url = `${this.baseUrl}/api/hidden-dates`;
      const response = await this.callWithAuthCheck('get', url);
      return response.success ? response.data : [];
    } catch (error) {
      console.error('获取隐藏日期列表失败:', error);
      return [];
    }
  }

  async getHiddenDatesByRange(startDate, endDate) {
    const url = `${this.baseUrl}/api/hidden-dates/range`;
    const params = { startDate, endDate };
    const response = await this.callWithAuthCheck('get', url, null, params);
    return response.success ? response.data : [];
  }

  async deleteHiddenDate(id) {
    const url = `${this.baseUrl}/api/hidden-dates/${id}`;
    const response = await this.callWithAuthCheck('delete', url);
    return response.success ? response.data : null;
  }

  // 需求参与人员相关接口
  async getRequirementParticipants(params = {}) {
    try {
      // 检查是否有缓存且未过期
      const now = Date.now();
      if (this.cachedParticipants && this.cachedParticipantsTimestamp &&
          (now - this.cachedParticipantsTimestamp) < this.cacheExpireTime) {
        console.log('使用缓存的参与人员数据');
        return this.cachedParticipants;
      }
      
      // 如果没有缓存或缓存已过期，重新请求数据
      const url = `${this.baseUrl}/api/requirement-participants`;
      const response = await this.callWithAuthCheck('get', url, null, params);
      
      if (response.success) {
        // 缓存数据
        this.cachedParticipants = response.data;
        this.cachedParticipantsTimestamp = now;
        console.log('已缓存参与人员数据');
        return response.data;
      } else {
        return [];
      }
    } catch (error) {
      console.error('获取需求参与人员列表失败:', error);
      return [];
    }
  }

  async getRequirementParticipantsByRequirement(requirementId) {
    const url = `${this.baseUrl}/api/requirement-participants/requirement/${requirementId}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async getRequirementParticipantsByMember(memberId) {
    const url = `${this.baseUrl}/api/requirement-participants/member/${memberId}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async addRequirementParticipant(participantData) {
    try {
      const url = `${this.baseUrl}/api/requirement-participants`;
      const response = await this.callWithAuthCheck('post', url, JSON.stringify(participantData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('新增参与人员失败:', error);
      return null;
    }
  }

  async updateRequirementParticipant(id, participantData) {
    try {
      const url = `${this.baseUrl}/api/requirement-participants`;
      // 确保在更新数据中包含ID
      const updateData = {
        ...participantData,
        id: id
      };
      const response = await this.callWithAuthCheck('put', url, JSON.stringify(updateData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('更新参与人员失败:', error);
      return null;
    }
  }

  async deleteRequirementParticipant(id) {
    const url = `${this.baseUrl}/api/requirement-participants/${id}`;
    const response = await this.callWithAuthCheck('delete', url);
    return response.success ? response.data : null;
  }

  // 批量新增需求参与人员
  async batchAddRequirementParticipants(batchData) {
    try {
      const url = `${this.baseUrl}/api/requirement-participants/batch`;
      const response = await this.callWithAuthCheck('post', url, JSON.stringify(batchData));
      return response.success ? response.data : null;
    } catch (error) {
      console.error('批量新增参与人员失败:', error);
      return null;
    }
  }

  // 操作日志相关接口
  async getOperationLogs() {
    const url = `${this.baseUrl}/api/operation-logs`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async getOperationLogsByTableAndRecord(tableName, recordId) {
    const url = `${this.baseUrl}/api/operation-logs/table/${tableName}/record/${recordId}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async getOperationLogsByOperatedBy(operatedBy) {
    const url = `${this.baseUrl}/api/operation-logs/operated-by/${operatedBy}`;
    const response = await this.callWithAuthCheck('get', url);
    return response.success ? response.data : [];
  }

  async deleteOperationLog(id) {
    const url = `${this.baseUrl}/api/operation-logs/${id}`;
    const response = await this.callWithAuthCheck('delete', url);
    return response.success ? response.data : null;
  }

  // 数据转换方法 - 将API返回的数据转换为前端需要的格式
  transformMemberData(member) {
    return {
      id: member.id?.toString(),
      name: member.name,
      type: member.type,
      authCode: member.authCode,
      isHidden: member.isHidden,
      isActive: member.isActive
    };
  }

  transformRequirementData(requirement) {
    // 计算开发工时：累加所有开发人员的workload（不去重）
    let devHours = 0;
    if (requirement.developers && Array.isArray(requirement.developers)) {
      devHours = requirement.developers.reduce((total, dev) => {
        if (typeof dev === 'object' && dev.workload !== undefined) {
          return total + (parseFloat(dev.workload) || 0);
        }
        return total;
      }, 0);
    } else {
      // 如果没有developers数组，使用原有的devHours字段
      devHours = requirement.devHours || 0;
    }

    // 计算测试工时：累加所有测试人员的workload（不去重）
    let testHours = 0;
    if (requirement.testers && Array.isArray(requirement.testers)) {
      testHours = requirement.testers.reduce((total, tester) => {
        if (typeof tester === 'object' && tester.workload !== undefined) {
          return total + (parseFloat(tester.workload) || 0);
        }
        return total;
      }, 0);
    } else {
      // 如果没有testers数组，使用原有的testHours字段
      testHours = requirement.testHours || 0;
    }

    // 去重开发人员列表（仅用于显示，不影响工时计算）
    const uniqueDevelopers = this.getUniqueDevelopers(requirement.developers || []);
    // 去重测试人员列表（仅用于显示，不影响工时计算）
    const uniqueTesters = this.getUniqueTesters(requirement.testers || []);

    return {
      id: requirement.id?.toString(),
      name: requirement.name,
      productManager: requirement.productManager,
      status: requirement.status,
      reviewTime: requirement.reviewTime,
      integrationTime: requirement.integrationTime,
      testTime: requirement.testTime,
      releaseTime: requirement.releaseTime,
      devHours: devHours,
      testHours: testHours,
      description: requirement.description,
      priority: requirement.priority,
      m1Address: requirement.m1Address,
      isActive: requirement.isActive,
      // 使用去重后的开发人员和测试人员列表（仅用于显示）
      developers: uniqueDevelopers,
      testers: uniqueTesters
    };
  }

  // 去重开发人员列表
  getUniqueDevelopers(developers) {
    if (!Array.isArray(developers)) return [];
    
    const seen = new Set();
    return developers.filter(dev => {
      const name = typeof dev === 'object' ? dev.name : dev;
      if (seen.has(name)) {
        return false;
      }
      seen.add(name);
      return true;
    });
  }

  // 去重测试人员列表
  getUniqueTesters(testers) {
    if (!Array.isArray(testers)) return [];
    
    const seen = new Set();
    return testers.filter(tester => {
      const name = typeof tester === 'object' ? tester.name : tester;
      if (seen.has(name)) {
        return false;
      }
      seen.add(name);
      return true;
    });
  }

  transformParticipantData(participant) {
    return {
      id: participant.id?.toString(),
      requirementId: participant.requirementId?.toString(),
      memberId: participant.memberId?.toString(),
      requirementName: participant.requirementName,
      memberName: participant.memberName,
      startTime: participant.startTime,
      endTime: participant.endTime,
      workload: participant.workload,
      role: participant.role,
      type: participant.type,
      workItem: participant.workItem
    };
  }

  transformHiddenDateData(hiddenDate) {
    return {
      id: hiddenDate.id?.toString(),
      dateValue: hiddenDate.dateValue,
      reason: hiddenDate.reason
    };
  }

  // 批量转换方法
  transformMembersData(members) {
    return members.map(member => this.transformMemberData(member));
  }

  transformRequirementsData(requirements) {
    return requirements.map(req => this.transformRequirementData(req));
  }

  transformParticipantsData(participants) {
    return participants.map(part => this.transformParticipantData(part));
  }

  transformHiddenDatesData(hiddenDates) {
    return hiddenDates.map(date => this.transformHiddenDateData(date));
  }

  transformProjectConfigData(config) {
    return {
      id: config.id?.toString(),
      configKey: config.configKey,
      configValue: config.configValue,
      description: config.description
    };
  }

  transformProjectConfigsData(configs) {
    return configs.map(config => this.transformProjectConfigData(config));
  }

  transformOperationLogData(log) {
    return {
      id: log.id?.toString(),
      tableName: log.tableName,
      recordId: log.recordId,
      operationType: log.operationType,
      oldValues: log.oldValues,
      newValues: log.newValues
    };
  }

  transformOperationLogsData(logs) {
    return logs.map(log => this.transformOperationLogData(log));
  }
}